package com.gator.zuul.fallback;

import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @Author PABLO
 * @Date 2022/5/23 13:50
 * @Desc zuul的熔断处理，只处理超时
 */
public class TargetServerFallback implements FallbackProvider {
    //配置需要熔断的服务
    @Override
    public String getRoute() {
        return "eureka-client";
    }

    //降级处理
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.GATEWAY_TIMEOUT;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                //code数值  如504  404  500 .....
                return this.getStatusCode().value();
            }

            @Override
            public String getStatusText() throws IOException {
                return this.getStatusCode().getReasonPhrase();
            }

            @Override
            public void close() {
                try {
                    this.getBody().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream("不可用请稍后再试".getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(new MediaType("application", "json", Charset.forName("utf-8")));
                return headers;
            }
        };
    }
}
